package com.zhongshengnetwork.rightbe.wzt.view;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.pj.core.utilities.ConvertUtility;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DateUtil;
import com.zhongshengnetwork.rightbe.common.activity.ReportActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.gsonmodel.CircleLangModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DryCommentModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangCommentActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.view.controller.CommonItemViewController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.CLIPBOARD_SERVICE;

public class WZTCommentRecyclerAdapter extends RecyclerView.Adapter<WZTCommentRecyclerAdapter.ViewHolder> {

    private List<DryCommentModel> list;
    public Context mContext;
    private long id;

    private List<String> moreList;
    private int opIndex = 0;
    private int shareType = 0;
    private boolean isShareWx = false;
    private String writer = "";

    private ClipboardManager myClipboard;

    public WZTCommentRecyclerAdapter(Context mContext, List<DryCommentModel>list, long id, String userid){
        this.mContext = mContext;
        this.list = list;
        this.id = id;
        this.writer = userid;
        myClipboard = (ClipboardManager)mContext.getSystemService(CLIPBOARD_SERVICE);
    }

    static class ViewHolder extends RecyclerView.ViewHolder{

        private ImageView drycomment_listview_item_header;
        private ImageView drycomment_listview_private_icon;
        private TextView drycomment_listview_item_name;
        private TextView drycomment_listview_item_time;
        private TextView drycomment_listview_item_content;

        private RelativeLayout drycomment_listview_item_reply;
        private TextView reply_text;
        private TextView replycount_text;

        private FrameLayout drycomment_listview_item_more;

        private RelativeLayout lang_like;
        private ImageView lang_like_img;
        private TextView lang_like_text;

        private RelativeLayout lang_collect;
        private ImageView lang_collect_img;
        private TextView lang_collect_text;

        private RelativeLayout comment_layout;
        private LinearLayout item_gas_line;

        private ImageView lang_member_icon;

        public ViewHolder(View view){
            super(view);

            drycomment_listview_item_header = (ImageView) view.findViewById(R.id.drycomment_listview_item_header);
            drycomment_listview_private_icon = (ImageView) view.findViewById(R.id.drycomment_listview_private_icon);
            drycomment_listview_item_name = (TextView) view.findViewById(R.id.drycomment_listview_item_name);
            drycomment_listview_item_time = (TextView) view.findViewById(R.id.drycomment_listview_item_time);
            drycomment_listview_item_content = (TextView) view.findViewById(R.id.drycomment_listview_item_content);

            drycomment_listview_item_reply = (RelativeLayout) view.findViewById(R.id.drycomment_listview_item_reply);
            reply_text = (TextView) view.findViewById(R.id.reply_text);
            replycount_text = (TextView) view.findViewById(R.id.replycount_text);

            drycomment_listview_item_more = (FrameLayout) view.findViewById(R.id.drycomment_listview_item_more);

            lang_like = (RelativeLayout) view.findViewById(R.id.lang_like);
            lang_like_img = (ImageView) view.findViewById(R.id.lang_like_img);
            lang_like_text = (TextView) view.findViewById(R.id.lang_like_text);

            lang_collect = (RelativeLayout) view.findViewById(R.id.lang_collect);
            lang_collect_img = (ImageView) view.findViewById(R.id.lang_collect_img);
            lang_collect_text = (TextView) view.findViewById(R.id.lang_collect_text);

            comment_layout = (RelativeLayout) view.findViewById(R.id.comment_layout);

            item_gas_line = (LinearLayout) view.findViewById(R.id.item_gas_line);

            lang_member_icon = (ImageView) view.findViewById(R.id.lang_member_icon);

        }

    }


    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_listview_item,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position)
    {
        Log.e("TAG", "position="+position);
        DryCommentModel model = list.get(position);

        holder.comment_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        holder.item_gas_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        holder.drycomment_listview_item_header.setClickable(true);
        holder.drycomment_listview_item_header.setTag(position);
        holder.drycomment_listview_item_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentUser((Integer) v.getTag());
            }
        });

        holder.drycomment_listview_private_icon.setClickable(true);
        holder.drycomment_listview_private_icon.setTag(position);
        holder.drycomment_listview_private_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentUser((Integer) v.getTag());
            }
        });

        holder.drycomment_listview_item_name.setClickable(true);
        holder.drycomment_listview_item_name.setTag(position);
        holder.drycomment_listview_item_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentUser((Integer) v.getTag());
            }
        });

        holder.drycomment_listview_item_more.setClickable(true);
        holder.drycomment_listview_item_more.setTag(position);
        holder.drycomment_listview_item_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentMore((Integer) v.getTag());
            }
        });

        holder.drycomment_listview_item_reply.setBackgroundResource(AppThemeUtils.getInstance().getCommentButtonBackground());
        holder.drycomment_listview_item_reply.setClickable(true);
        holder.drycomment_listview_item_reply.setTag(position);
        holder.drycomment_listview_item_reply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentReply((Integer) v.getTag(), true);
            }
        });

        /*
        int replyCount = ConvertUtility.parseInt(model.getCcount());
        if (replyCount > 999){
            holder.reply_text.setText((float)replyCount/1000.0f + "k回复");
        }else {
            if (replyCount > 0) {
                holder.reply_text.setText(replyCount + "回复");
            } else {
                holder.reply_text.setText("回复");
            }
        }
        */
        holder.reply_text.setText("回复");

        holder.replycount_text.setTag(position);
        int count = Integer.valueOf(model.getCcount());// + model.getReplycount();
        if (count > 0){
            holder.replycount_text.setVisibility(View.VISIBLE);
            holder.replycount_text.setText("查看"+count+"条回复 >");
        }else {
            holder.replycount_text.setVisibility(View.INVISIBLE);
        }
        holder.replycount_text.setClickable(true);
        holder.replycount_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commentReply((int)view.getTag(), false);
            }
        });

        holder.lang_like.setVisibility(View.VISIBLE);
        holder.lang_like.setTag(position);
        holder.lang_like.setFocusable(false);
        holder.lang_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentLike((Integer) v.getTag());
            }
        });

        if (model.getIslike().equals("1")){
            holder.lang_like_img.setImageResource(R.drawable.workgroup_img_like_sel);
            holder.lang_like_text.setTextColor(ContextCompat.getColor(mContext,R.color.lightGreenColor));
        }else {
            holder.lang_like_img.setImageResource(R.drawable.workgroup_img_like);
            holder.lang_like_text.setTextColor(AppThemeUtils.getInstance().getSmallTextColor());
        }
        if (ConvertUtility.parseInt(model.getLcount()) < 1) {
            holder.lang_like_text.setText("笔芯");
        } else {
            holder.lang_like_text.setText(model.getLcount());
        }

        holder.lang_collect.setVisibility(View.VISIBLE);
        holder.lang_collect.setTag(position);
        holder.lang_collect.setFocusable(false);
        holder.lang_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commentCollect((Integer) v.getTag());
            }
        });
        ImageView collect_icon = holder.lang_collect_img;
        TextView collect_count = holder.lang_collect_text;
        if (model.getIscollect().equals("1")){
            collect_icon.setImageResource(R.drawable.collection_sel);
            collect_count.setTextColor(ContextCompat.getColor(mContext,R.color.lightGreenColor));
        }else {
            collect_icon.setImageResource(R.drawable.collection);
            collect_count.setTextColor(ContextCompat.getColor(mContext,R.color.defaultSmallFontColor));
        }
        collect_count.setText(ConvertUtility.parseInt(model.getCollectcount()) < 1 ? "收藏" : model.getCollectcount());

        Glide.with(mContext).load(model.getHeader()).transform(new CircleTransform(mContext)).dontAnimate().into(holder.drycomment_listview_item_header);
        if (!CommonUtils.isEmpty(model.getPrivateIcon())){
            holder.drycomment_listview_private_icon.setVisibility(View.VISIBLE);
            Glide.with(mContext).load(model.getPrivateIcon()).transform(new CircleTransform(mContext)).dontAnimate().into(holder.drycomment_listview_private_icon);
        }else {
            holder.drycomment_listview_private_icon.setVisibility(View.INVISIBLE);
        }

        String lcount = CommonUtils.getDisplayCount(Integer.valueOf(model.getLcount()));
        String s1 = DateUtil.getChatDate(Long.valueOf(model.getTime()))+"";
        holder.drycomment_listview_item_time.setText(s1);
        if (writer.equals(model.getUserid())){
            holder.drycomment_listview_item_time.setText("作者  ·  "+s1);
        }

        holder.drycomment_listview_item_time.setTag(position);
        holder.drycomment_listview_item_time.setFocusable(false);


        holder.drycomment_listview_item_name.setText(model.getNickname());
        holder.drycomment_listview_item_content.setTag(position);
        holder.drycomment_listview_item_content.setText(model.getContent());
        holder.drycomment_listview_item_content.setFocusable(false);

        holder.drycomment_listview_item_name.setTextColor(AppThemeUtils.getInstance().getUserNameColorOfWeiJu());
        holder.drycomment_listview_item_content.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        if (!CommonUtils.isEmpty(model.getMemberIcon())){
            holder.lang_member_icon.setVisibility(View.VISIBLE);
            if (mContext != null){
                try{
                    Glide.with(mContext).load(model.getMemberIcon()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(holder.lang_member_icon);
                }catch (Exception e){
                    LangPublishActivity.uploadError("微纸条评论列表加载图片报错："+e.getLocalizedMessage());
                }
            }
        }else {
            holder.lang_member_icon.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public int getItemCount() {
        return this.list.size();
    }

    //点击了评论用户
    private void commentUser(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        final DryCommentModel model = list.get(index);
        //进入个人主页
        Intent intent = new Intent(mContext, UserLangActivity.class);
        intent.putExtra(APIKey.useridKey,model.getUserid());
        intent.putExtra(APIKey.typeKey,1);
        intent.putExtra(APIKey.titleKey,model.getNickname());
        mContext.startActivity(intent);
    }

    //评论点击更多
    private void commentMore(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        if (moreList == null){
            moreList = new ArrayList<>();
        }
        final DryCommentModel model = list.get(index);
        shareType = 0;
        opIndex = index;
        moreList.clear();
        moreList.add("回复");
        if (model.getIslike().equals("0")){
            moreList.add("笔芯");
        }
        if (model.getIscollect().equals("0")){
            moreList.add("收藏");
        }
        moreList.add("复制");
        if (CommonUtils.isLogin() == true){
            if (CustomApplication.loginModel.getUid().equals(model.getUserid()) || CustomApplication.loginModel.getUid().equals(writer)){
                moreList.add("删除");
            }
        }
        moreList.add("举报");

        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(mContext)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : moreList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        String title = moreList.get(which-1);
                        if (title.equals("回复")){
                            commentReply(index,true);
                        }else if (title.equals("笔芯")){
                            commentLike(index);
                        }else if (title.equals("收藏")){
                            commentCollect(index);
                        }else if (title.equals("删除")){

                            CustomDialog dialog = null;
                            final CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                            builder.setTitle("温馨提示");
                            builder.setMessage("确定要删除？");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    commentDelete(index);
                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            dialog = builder.create();
                            dialog.show();

                        }else if (title.equals("复制")){
                            onClickCopy(model.getContent());
                        }else if (title.equals("举报")){
                            report(model.getCommentid(), Constant.ReportWZTCommentType);
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    //评论笔芯
    private void commentLike(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(mContext, LoginActivity.class);
            mContext.startActivity(intent);
            return;
        }
        final DryCommentModel model = list.get(index);
        if(CommonUtils.isEmpty(model.getCommentid())){
            return;
        }
        int count = Integer.valueOf(model.getLcount());
        if (model.getIslike().equals("1")){
            if (count > 0){
                count -= 1;
            }
            model.setIslike("0");
        }else {
            count += 1;
            model.setIslike("1");
        }
        model.setLcount(count+"");
        list.set(index,model);
        notifyItemChanged(index);

        new Thread(){
            @Override
            public void run() {
                super.run();
                final Map<String,String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey,CustomApplication.loginModel.getToken());
                map.put(APIKey.idKey,model.getCommentid());
                String url = "weishu/theme/comment/like.do";
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                    }

                    @Override
                    public void onError(String msg) {
                    }
                });
            }
        }.start();
    }

    //评论收藏
    private void commentCollect(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(mContext,LoginActivity.class);
            mContext.startActivity(intent);
            return;
        }
        final DryCommentModel model = list.get(index);
        if(CommonUtils.isEmpty(model.getCommentid())){
            return;
        }
        if (model.getIscollect().equals("1")){
            model.setIscollect("0");
            model.setCollectcount(Integer.valueOf(model.getCollectcount())-1+"");
        }else {
            model.setIscollect("1");
            model.setCollectcount(Integer.valueOf(model.getCollectcount())+1+"");
        }

        notifyItemChanged(index);

        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
                map.put("sourceid", model.getCommentid());
                map.put(APIKey.typeKey,"3");
                String url = "miniapp/"+"langappid"+"/addcollection.do";
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        Log.e("TAG","收藏结果："+data);
                    }

                    @Override
                    public void onError(String msg) {
                    }
                });
            }
        }.start();
    }

    //评论删除
    private void commentDelete(final int index){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(mContext,LoginActivity.class);
            mContext.startActivity(intent);
            return;
        }
        final DryCommentModel model = list.get(index);
        if(CommonUtils.isEmpty(model.getCommentid())){
            return;
        }

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("id", model.getCommentid());
        map.put(APIKey.typeKey,"0");
        String url = "weishu/theme/comment/delete.do";

        list.remove(model);
        notifyDataSetChanged();

        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("TAG","删除结果："+data);
            }

            @Override
            public void onError(String msg) {
            }
        });
    }

    //评论回复
    private void commentReply(final int index, boolean isReply){
        if (list == null || list.size() == 0){
            return;
        }
        DryCommentModel model = list.get(index);
        if (!CommonUtils.isEmpty(model.getCommentid())){
            Intent intent = new Intent(mContext, LangCommentActivity.class);
            intent.putExtra("id",id+"");
            Bundle bundle = new Bundle();
            bundle.putSerializable("DryCommentModel", model);
            intent.putExtras(bundle);
            intent.putExtra("isReply",isReply);
            intent.putExtra("type",1);
            mContext.startActivity(intent);
        }
    }

    private void report(String reportId, int reportType){//reportType:1-举报人；2-举报微句；3-举报评论；4-举报微纸条；5-举报微纸条内容；6-举报微纸条评论
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(mContext,LoginActivity.class);
            mContext.startActivity(intent);
            return;
        }
        Intent intent = new Intent(mContext, ReportActivity.class);
        intent.putExtra(APIKey.idKey,reportId);
        intent.putExtra(APIKey.typeKey,reportType);
        mContext.startActivity(intent);
    }

    private void onClickCopy(String text){
        try{
            ClipData myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);
            Toast.makeText(mContext, "内容已复制~",
                    Toast.LENGTH_SHORT).show();
        }catch (Exception e){

        }
    }

}
